<!-- TreeNode.vue -->
<template>
	<component :is="tag">
		<div>
			<div v-for="(item, index) in treeData" :key="index" @click="toggle(index, item)"
				:class="{ 'active-item': activeChildIndex === index }">
				<div style="font-size: 18px;padding: 5px 0;">{{ item.name }}
				</div>
				<!-- 移除了箭头图标代码，根据需求可自行恢复 -->
				<ul v-if="item.children && activeChildIndex === index" v-show="activeChildIndex === index">
					<tree-node :treeData="item.children" @toggle="toggleChildren"></tree-node>
				</ul>
			</div>
		</div>
	</component>
</template>

<script>
import TreeNode from './TreeNode.vue'; // 确保路径正确，如果是外部引入需修正

export default {
	name: 'TreeNode',
	components: {
		TreeNode
	},
	props: {
		treeData: {
			type: Array,
			required: true
		},
		tag: {
			type: String,
			default: 'li'
		},
		activeCIndex: {
			type: Number,
			default: null
		}
	},
	watch: {
		activeCIndex: {
			handler(newVal, oldVal) {
				this.activeChildIndex = newVal;
			},
			deep: true,
			immediate: true
		}
	},
	data() {
		return {
			activeChildIndex: null // 存储1当前激活子节点的索引
		};
	},
	methods: {
		toggle(index, item) {
			console.log(item);
			this.$emit('toggle', index);
			this.activeChildIndex = index; // 直接在当前组件管理高亮状态
			this.$emit('node-clicked', item);
		},
		toggleChildren(index) {
			this.$emit('toggleChildren', index);
		}
	},
	mounted() {
		if (this.activeCIndex) {
			this.activeChildIndex = this.activeCIndex;
		}
	}
};
</script>

<style scoped>
.active-item {
	border-left: 2px solid #3eaf7c;
	color: #3eaf7c;

}
</style>